import { reqGetCode, reqUserRegister, reqUserLogin, reqUserIinfo, reqLogOut } from '@/api/index'
import { setToKen, removeToken, getToKen } from '@/utils/toKen'
// 登录与注册模块
const state = {
  code: '',
  // 用户token
  // userToken: localStorage.getItem("TOKEN"),
  userToken: getToKen(),
  // 用户信息
  userInfo: {}
}
const mutations = {
  // 验证码
  GETCODE(state, code) {
    state.code = code
  },
  // 登录
  USERLOGIN(state, userToken) {
    state.userToken = userToken
  },
  // 用户信息
  GETUSERINFO(state, userInfo) {
    state.userInfo = userInfo
  },
  // 退出登录
  CLEAR(state) {
    //清除仓库相关用户信息
    state.userToken = '';
    state.userInfo = '';
    //本地存储令牌清空
    // localStorage.removeItem('TOKEN');
    removeToken()
  }
}
const actions = {
  // 获取验证码
  async getCode({ commit }, phone) {
    let result = await reqGetCode(phone)
    if (result.code == 200) {
      commit('GETCODE', result.data)
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  // 用户注册
  async userRegister({ commit }, user) {
    let result = await reqUserRegister(user)
    console.log(result);
    if (result.code == 200) {
      console.log(result);
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  // async userRegister({ commit, state, dispatch }, obj) {
  //   //注册接口没有返回data,不需要提交mutation
  //   let result = await reqUserRegister(obj);
  //   if (result.code == 200) {
  //     //注册成功
  //     return 'ok';
  //   } else {
  //     //注册失败
  //     return Promise.reject(new Error(result.message));
  //   }
  // },

  // 用户登录业务
  async userLogin({ commit }, data) {
    let result = await reqUserLogin(data)
    // console.log(result);
    if (result.code == 200) {
      commit('USERLOGIN', result.data.token)
      // 持久化存储token
      setToKen(result.data.token)
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  
  // 获取用户信息
  async getUserInfo({ commit }) {
    let result = await reqUserIinfo()
    if (result.code == 200) {
      commit('GETUSERINFO', result.data)
    } else {
      return Promise.reject()
    }
  },
  // 退出登录
  async userLginOut({ commit }) {
    let result = await reqLogOut()
    if (result.code == 200) {
      commit('CLEAR')
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  }


}
const getters = {

}

export default {
  state,
  mutations,
  actions,
  getters,
}